﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using System.IO;

using MEFedMVVM.ViewModelLocator;
using Cinch;
using System.Configuration;
using System.Data;

namespace Anata.Client
{

    /// <summary>
    /// Runtime implementation of the 
    /// Data service used by the <c>ImageLoaderViewModel</c> to obtain data
    /// </summary>
    [PartCreationPolicy(CreationPolicy.NonShared)]
    [ExportService(ServiceType.Runtime, typeof(ICabangProvider))]
    public class CabangProvider : ICabangProvider
    {
        #region Data
        private BackgroundTaskManager<int, List<CabangThumbnailViewModel>> multiFetchTVMBgWorker =
            new BackgroundTaskManager<int, List<CabangThumbnailViewModel>>();
        private BackgroundTaskManager<CabangThumbnailViewModel, CabangThumbnailViewModel> singleUpdateTVMBgWorker =
            new BackgroundTaskManager<CabangThumbnailViewModel, CabangThumbnailViewModel>();
        private BackgroundTaskManager<CabangViewModel, CabangViewModel> singleUpdateVMBgWorker =
            new BackgroundTaskManager<CabangViewModel, CabangViewModel>();
        #endregion

        #region Data [NEW]
        private BackgroundTaskManager<int, List<SimpleCabangViewModel>> multiFetchSVMBgWorker =
            new BackgroundTaskManager<int, List<SimpleCabangViewModel>>();
        private BackgroundTaskManager<ComplexCabangViewModel, ComplexCabangViewModel> singleUpdateCVMBgWorker =
            new BackgroundTaskManager<ComplexCabangViewModel, ComplexCabangViewModel>();

        private BackgroundTaskManager<PopupStokViewModel, PopupStokViewModel> singleUpdatePVMBgWorker =
            new BackgroundTaskManager<PopupStokViewModel, PopupStokViewModel>();
        #endregion

        #region PublicMethods
        public void LazyFetchCabangs(int page, Action<List<CabangThumbnailViewModel>> callback) 
        {
            BackgroundTaskManager<int, List<CabangThumbnailViewModel>> bgWorker = null;
            if (multiFetchTVMBgWorker.TaskFunc != null)
            {
                bgWorker = new BackgroundTaskManager<int, List<CabangThumbnailViewModel>>();
            }
            else
            {
                bgWorker = multiFetchTVMBgWorker;
            }

            bgWorker.TaskFunc = (argument) =>
            {
                return FetchCabangTVMsInternal(argument);
            };

            bgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            bgWorker.WorkerArgument = page;
            bgWorker.RunBackgroundTask();
        }
        public void LazyLoadCabang(CabangThumbnailViewModel ctvm, Action<CabangThumbnailViewModel> callback)
        {
            BackgroundTaskManager<CabangThumbnailViewModel, CabangThumbnailViewModel> bgWorker = null;
            if (singleUpdateTVMBgWorker.TaskFunc != null)
            {
                bgWorker = new BackgroundTaskManager<CabangThumbnailViewModel, CabangThumbnailViewModel>();
            }
            else
            {
                bgWorker = singleUpdateTVMBgWorker;
            }

            bgWorker.TaskFunc = (argument) =>
            {
                return LoadCabangTVMInternal(argument);
            };

            bgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            bgWorker.WorkerArgument = ctvm;
            bgWorker.RunBackgroundTask();
        }
        public void LazySaveCabang(CabangThumbnailViewModel ctvm, Action<CabangThumbnailViewModel> callback)
        {
            BackgroundTaskManager<CabangThumbnailViewModel, CabangThumbnailViewModel> bgWorker = null;
            if (singleUpdateTVMBgWorker.TaskFunc != null)
            {
                bgWorker = new BackgroundTaskManager<CabangThumbnailViewModel, CabangThumbnailViewModel>();
            }
            else
            {
                bgWorker = singleUpdateTVMBgWorker;
            }

            bgWorker.TaskFunc = (argument) =>
            {
                return SaveCabangTVMInternal(argument);
            };

            bgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            bgWorker.WorkerArgument = ctvm;
            bgWorker.RunBackgroundTask();
        }
        public void LazyRemoveCabang(CabangThumbnailViewModel ctvm, Action<CabangThumbnailViewModel> callback)
        {
            BackgroundTaskManager<CabangThumbnailViewModel, CabangThumbnailViewModel> bgWorker = null;
            if (singleUpdateTVMBgWorker.TaskFunc != null)
            {
                bgWorker = new BackgroundTaskManager<CabangThumbnailViewModel, CabangThumbnailViewModel>();
            }
            else
            {
                bgWorker = singleUpdateTVMBgWorker;
            }

            bgWorker.TaskFunc = (argument) =>
            {
                return RemoveCabangTVMInternal(argument);
            };

            bgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            bgWorker.WorkerArgument = ctvm;
            bgWorker.RunBackgroundTask();
        }
        public void LazyLoadCabang(CabangViewModel cvm, Action<CabangViewModel> callback)
        {
            BackgroundTaskManager<CabangViewModel, CabangViewModel> bgWorker = null;
            if (singleUpdateVMBgWorker.TaskFunc != null)
            {
                bgWorker = new BackgroundTaskManager<CabangViewModel, CabangViewModel>();
            }
            else
            {
                bgWorker = singleUpdateVMBgWorker;
            }

            bgWorker.TaskFunc = (argument) =>
            {
                return LoadCabangVMInternal(argument);
            };

            bgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            bgWorker.WorkerArgument = cvm;
            bgWorker.RunBackgroundTask();
        }
        public void LazySaveCabang(CabangViewModel cvm, Action<CabangViewModel> callback)
        {
            BackgroundTaskManager<CabangViewModel, CabangViewModel> bgWorker = null;
            if (singleUpdateVMBgWorker.TaskFunc != null)
            {
                bgWorker = new BackgroundTaskManager<CabangViewModel, CabangViewModel>();
            }
            else
            {
                bgWorker = singleUpdateVMBgWorker;
            }

            bgWorker.TaskFunc = (argument) =>
            {
                return SaveCabangVMInternal(argument);
            };

            bgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            bgWorker.WorkerArgument = cvm;
            bgWorker.RunBackgroundTask();
        }
        public void LazyRemoveCabang(CabangViewModel cvm, Action<CabangViewModel> callback)
        {
            BackgroundTaskManager<CabangViewModel, CabangViewModel> bgWorker = null;
            if (singleUpdateVMBgWorker.TaskFunc != null)
            {
                bgWorker = new BackgroundTaskManager<CabangViewModel, CabangViewModel>();
            }
            else
            {
                bgWorker = singleUpdateVMBgWorker;
            }

            bgWorker.TaskFunc = (argument) =>
            {
                return RemoveCabangVMInternal(argument);
            };

            bgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            bgWorker.WorkerArgument = cvm;
            bgWorker.RunBackgroundTask();
        }
        #endregion


        #region PublicMethods [NEW]
        public void LazyFetchCabangs(int page, Action<List<SimpleCabangViewModel>> callback)
        {
            multiFetchSVMBgWorker.TaskFunc = (argument) =>
            {
                return FetchCabangsInternal(argument);
            };

            multiFetchSVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            multiFetchSVMBgWorker.WorkerArgument = page;
            multiFetchSVMBgWorker.RunBackgroundTask();
        }

        public void LazyLoadCompleteCabang(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return LoadCompleteCabangInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }
        public void LazyLoadCabang(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return LoadCabangInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }
        public void LazyLoadCabangLayanan(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return LoadCabangLayananInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }
        public void LazyLoadCabangProduk(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return LoadCabangProdukInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }
        public void LazyLoadCabangRekening(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return LoadCabangRekeningInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }
        public void LazyLoadFreeGift(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return LoadFreeGiftInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }
        public void LazyLoadPromo(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return LoadPromoInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }
        public void LazyLoadAset(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return LoadAsetInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }
        public void LazyLoadStok(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return LoadStokInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }

        public void LazySaveCompleteCabang(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return SaveCompleteCabangInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }
        public void LazySaveCabang(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return SaveCabangInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }
        public void LazySaveCabangLayanan(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return SaveCabangLayananInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }
        public void LazySaveCabangProduk(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return SaveCabangProdukInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }
        public void LazySaveCabangRekening(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return SaveCabangRekeningInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }
        public void LazySaveFreeGift(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return SaveFreeGiftInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }
        public void LazySavePromo(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return SavePromoInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }
        public void LazySaveAset(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return SaveAsetInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }
        public void LazySaveStok(ComplexCabangViewModel ccvm, Action<ComplexCabangViewModel> callback)
        {
            singleUpdateCVMBgWorker.TaskFunc = (argument) =>
            {
                return SaveStokInternal(argument);
            };

            singleUpdateCVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdateCVMBgWorker.WorkerArgument = ccvm;
            singleUpdateCVMBgWorker.RunBackgroundTask();
        }



        public void LazyLoadCompleteStok(PopupStokViewModel ccvm, Action<PopupStokViewModel> callback)
        {
            singleUpdatePVMBgWorker.TaskFunc = (argument) =>
            {
                return LoadCompleteStokInternal(argument);
            };

            singleUpdatePVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdatePVMBgWorker.WorkerArgument = ccvm;
            singleUpdatePVMBgWorker.RunBackgroundTask();
        }
        public void LazyLoadStok(PopupStokViewModel ccvm, Action<PopupStokViewModel> callback)
        {
            singleUpdatePVMBgWorker.TaskFunc = (argument) =>
            {
                return LoadStokInternal(argument);
            };

            singleUpdatePVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdatePVMBgWorker.WorkerArgument = ccvm;
            singleUpdatePVMBgWorker.RunBackgroundTask();
        }
        public void LazyLoadMutasiStok(PopupStokViewModel ccvm, Action<PopupStokViewModel> callback)
        {
            singleUpdatePVMBgWorker.TaskFunc = (argument) =>
            {
                return LoadMutasiStokInternal(argument);
            };

            singleUpdatePVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdatePVMBgWorker.WorkerArgument = ccvm;
            singleUpdatePVMBgWorker.RunBackgroundTask();
        }
        public void LazySaveCompleteStok(PopupStokViewModel ccvm, Action<PopupStokViewModel> callback)
        {
            singleUpdatePVMBgWorker.TaskFunc = (argument) =>
            {
                return SaveCompleteStokInternal(argument);
            };

            singleUpdatePVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdatePVMBgWorker.WorkerArgument = ccvm;
            singleUpdatePVMBgWorker.RunBackgroundTask();
        }
        public void LazySaveStok(PopupStokViewModel ccvm, Action<PopupStokViewModel> callback)
        {
            singleUpdatePVMBgWorker.TaskFunc = (argument) =>
            {
                return SaveStokInternal(argument);
            };

            singleUpdatePVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdatePVMBgWorker.WorkerArgument = ccvm;
            singleUpdatePVMBgWorker.RunBackgroundTask();
        }
        public void LazySaveMutasiStok(PopupStokViewModel ccvm, Action<PopupStokViewModel> callback)
        {
            singleUpdatePVMBgWorker.TaskFunc = (argument) =>
            {
                return SaveMutasiStokInternal(argument);
            };

            singleUpdatePVMBgWorker.CompletionAction = (result) =>
            {
                callback(result);
            };

            singleUpdatePVMBgWorker.WorkerArgument = ccvm;
            singleUpdatePVMBgWorker.RunBackgroundTask();
        }
        #endregion


        #region PublicProperties
        /// <summary>
        /// To allow this class to be unit tested stand alone
        /// See CinchV1 articles about Unit Testing for this
        /// Or comments in Cinch BackgroundTaskManager<T> class
        /// </summary>
        public BackgroundTaskManager<int, List<CabangThumbnailViewModel>> MultiFetchTVMBgWorker
        {
            get { return multiFetchTVMBgWorker; }
        }
        public BackgroundTaskManager<CabangThumbnailViewModel, CabangThumbnailViewModel> SingleUpdateTVMBgWorker
        {
            get { return singleUpdateTVMBgWorker; }
        }
        public BackgroundTaskManager<CabangViewModel, CabangViewModel> SingleUpdateVMBgWorker
        {
            get { return singleUpdateVMBgWorker; }
        }
        #endregion

        #region PrivateMethods
        private List<CabangThumbnailViewModel> FetchCabangTVMsInternal(int page)
        {
            List<CabangThumbnailViewModel> retval = new List<CabangThumbnailViewModel>();
            CabangThumbnailViewModel ctvm = null;
            try
            {
                int pageSize = Int32.Parse(ConfigurationManager.AppSettings["LazyLoadPageSize"].ToString());
                using (AnataEntities context = new AnataEntities())
                {
                    var query = from cabang in context.Cabang
                                orderby cabang.Nama
                                select cabang;
                    foreach (var cabang in query.Skip(page * pageSize).Take(pageSize).ToList())
                    {
                        ctvm = new CabangThumbnailViewModel();
                        SynchCabangToCTVM(cabang, ctvm);
                        retval.Add(ctvm);
                    }
                }
            }
            catch (Exception) { }
            return retval;
        }
        private CabangThumbnailViewModel LoadCabangTVMInternal(CabangThumbnailViewModel ctvm)
        {
            CabangThumbnailViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang original = (from cabang in context.Cabang
                                       where cabang.IdCabang == ctvm.IdCabang
                                       select cabang).First();
                    SynchCabangToCTVM(original, ctvm);
                    retval = ctvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private CabangThumbnailViewModel SaveCabangTVMInternal(CabangThumbnailViewModel ttvm)
        {
            CabangThumbnailViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    //Transaksi original = null;
                    //List<int> originalTLs = new List<int>();
                    //List<int> originalTPs = new List<int>();
                    //List<int> originalTBs = new List<int>();
                    //if (ttvm.IdTransaksi != 0)
                    //{
                    //    original = (from transaksi in context.Transaksi
                    //                where transaksi.IdTransaksi == ttvm.IdTransaksi
                    //                select transaksi).ToList().FirstOrDefault();
                    //    foreach (var tl in original.TransaksiLayanan)
                    //    {
                    //        originalTLs.Add(tl.IdTransaksiLayanan);
                    //    }
                    //    foreach (var tp in original.TransaksiProduk)
                    //    {
                    //        originalTPs.Add(tp.IdTransaksiProduk);
                    //    }
                    //    foreach (var tb in original.TransaksiPembayaran)
                    //    {
                    //        originalTBs.Add(tb.IdTransaksiPembayaran);
                    //    }
                    //}
                    //else
                    //{
                    //    original = context.Transaksi.CreateObject();
                    //    context.Transaksi.AddObject(original);
                    //    //TODO: Id Cabang & User
                    //    original.IdCabang = Int32.Parse(ConfigurationManager.AppSettings["IdCabang"].ToString());
                    //    original.WaktuBuat = DateTime.Now;
                    //    //originalTransaksi.IdUser = SessionController.Instance.LoggedUserId;
                    //    original.LastUpdated = DateTime.Now;
                    //}
                    //original.IdKonsumen = ttvm.IdKonsumen;
                    //original.WaktuSelesai = ttvm.WaktuSelesai;
                    //original.TotalHarga = ttvm.TotalHarga;
                    //original.PotonganHarga = ttvm.TotalPotongan;
                    //original.KoreksiHarga = ttvm.KoreksiHarga;
                    //original.IsBatal = ttvm.IsBatal;

                    //if (original.EntityState == EntityState.Modified)
                    //{
                    //    //originalTransaksi.IdUser = SessionController.Instance.LoggedUserId;
                    //    original.LastUpdated = DateTime.Now;
                    //}

                    //TransaksiLayanan originalTL = null;
                    //foreach (TransaksiLayananThumbnailViewModel tltvm in ttvm.TransaksiLayanans)
                    //{
                    //    if (originalTLs.Remove(tltvm.IdTransaksiLayanan))
                    //    {
                    //        originalTL = original.TransaksiLayanan.First(
                    //            tl => tl.IdTransaksiLayanan == tltvm.IdTransaksiLayanan);
                    //    }
                    //    else
                    //    {
                    //        originalTL = context.TransaksiLayanan.CreateObject();
                    //        context.TransaksiLayanan.AddObject(originalTL);
                    //        original.TransaksiLayanan.Add(originalTL);
                    //        originalTL.WaktuBuat = DateTime.Now;
                    //        //originalTL.IdUser = SessionController.Instance.LoggedUserId;
                    //        originalTL.LastUpdated = DateTime.Now;
                    //    }
                    //    originalTL.IdLayanan = tltvm.IdLayanan;
                    //    originalTL.HargaLayanan = tltvm.HargaLayanan;
                    //    originalTL.IdKaryawan = tltvm.IdKaryawan;
                    //    originalTL.NamaPromo = tltvm.NamaPromo;
                    //    originalTL.PotonganPromo = tltvm.PotonganPromo;
                    //    originalTL.NamaFreeGift = tltvm.NamaFreeGift;
                    //    originalTL.IdJenisStok = tltvm.IdJenisStok;
                    //    originalTL.JumlahFreeGift = tltvm.JumlahFreeGift;
                    //    originalTL.WaktuBuat = tltvm.WaktuBuat;
                    //    originalTL.WaktuTunggu = tltvm.WaktuTunggu;
                    //    originalTL.WaktuMulai = tltvm.WaktuMulai;
                    //    originalTL.WaktuSelesai = tltvm.WaktuSelesai;
                    //    originalTL.IsBatal = tltvm.IsBatal;

                    //    if (originalTL.EntityState == EntityState.Modified)
                    //    {
                    //        //originalTL.IdUser = SessionController.Instance.LoggedUserId;
                    //        originalTL.LastUpdated = DateTime.Now;
                    //    }
                    //}
                    ////clearing
                    //foreach (int removedId in originalTLs)
                    //{
                    //    context.TransaksiLayanan.DeleteObject(
                    //        original.TransaksiLayanan.First(
                    //            tl => tl.IdTransaksiLayanan == removedId));
                    //}

                    //TransaksiProduk originalTP = null;
                    //foreach (TransaksiProdukThumbnailViewModel tptvm in ttvm.TransaksiProduks)
                    //{
                    //    if (originalTPs.Remove(tptvm.IdTransaksiProduk))
                    //    {
                    //        originalTP = original.TransaksiProduk.First(
                    //            tp => tp.IdTransaksiProduk == tptvm.IdTransaksiProduk);
                    //    }
                    //    else
                    //    {
                    //        originalTP = context.TransaksiProduk.CreateObject();
                    //        context.TransaksiProduk.AddObject(originalTP);
                    //        original.TransaksiProduk.Add(originalTP);
                    //        //originalTP.IdUser = SessionController.Instance.LoggedUserId;
                    //        originalTP.LastUpdated = DateTime.Now;
                    //    }
                    //    originalTP.IdJenisStok = tptvm.IdJenisStok;
                    //    originalTP.IdKaryawan = tptvm.IdKaryawan;
                    //    originalTP.JumlahProduk = tptvm.JumlahProduk;
                    //    originalTP.HargaProduk = tptvm.HargaProduk;
                    //    originalTP.PotonganHarga = tptvm.PotonganHarga;

                    //    if (originalTP.EntityState == EntityState.Modified)
                    //    {
                    //        //originalTP.IdUser = SessionController.Instance.LoggedUserId;
                    //        originalTP.LastUpdated = DateTime.Now;
                    //    }
                    //}
                    ////clearing
                    //foreach (int removedId in originalTPs)
                    //{
                    //    context.TransaksiProduk.DeleteObject(
                    //        original.TransaksiProduk.First(
                    //            tp => tp.IdTransaksiProduk == removedId));
                    //}

                    //TransaksiPembayaran originalTB = null;
                    //foreach (TransaksiPembayaranThumbnailViewModel tbtvm in ttvm.TransaksiPembayarans)
                    //{
                    //    if (originalTBs.Remove(tbtvm.IdTransaksiPembayaran))
                    //    {
                    //        originalTB = original.TransaksiPembayaran.First(
                    //            tb => tb.IdTransaksiPembayaran == tbtvm.IdTransaksiPembayaran);
                    //    }
                    //    else
                    //    {
                    //        originalTB = context.TransaksiPembayaran.CreateObject();
                    //        context.TransaksiPembayaran.AddObject(originalTB);
                    //        original.TransaksiPembayaran.Add(originalTB);
                    //        //originalTB.IdUser = SessionController.Instance.LoggedUserId;
                    //        originalTB.LastUpdated = DateTime.Now;
                    //    }
                    //    originalTB.IdJenisPembayaran = tbtvm.IdJenisPembayaran;
                    //    originalTB.NominalPembayaran = tbtvm.NominalPembayaran;

                    //    if (originalTB.EntityState == EntityState.Modified)
                    //    {
                    //        //originalTB.IdUser = SessionController.Instance.LoggedUserId;
                    //        originalTB.LastUpdated = DateTime.Now;
                    //    }
                    //}
                    ////clearing
                    //foreach (int removedId in originalTBs)
                    //{
                    //    context.TransaksiPembayaran.DeleteObject(
                    //        original.TransaksiPembayaran.First(
                    //            tl => tl.IdTransaksiPembayaran == removedId));
                    //}
                    //context.SaveChanges();

                    ////update ids ++ synch
                    //SynchTransaksiToTTVM(original, ttvm);
                    //retval = ttvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private CabangThumbnailViewModel RemoveCabangTVMInternal(CabangThumbnailViewModel ttvm)
        {
            CabangThumbnailViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    //Transaksi original = null;
                    //List<int> originalTLs = new List<int>();
                    //List<int> originalTPs = new List<int>();
                    //List<int> originalTBs = new List<int>();
                    //if (ttvm.IdTransaksi != 0)
                    //{
                    //    original = (from transaksi in context.Transaksi
                    //                where transaksi.IdTransaksi == ttvm.IdTransaksi
                    //                select transaksi).ToList().FirstOrDefault();
                    //    foreach (var tl in original.TransaksiLayanan)
                    //    {
                    //        originalTLs.Add(tl.IdTransaksiLayanan);
                    //    }
                    //    foreach (var tp in original.TransaksiProduk)
                    //    {
                    //        originalTPs.Add(tp.IdTransaksiProduk);
                    //    }
                    //    foreach (var tb in original.TransaksiPembayaran)
                    //    {
                    //        originalTBs.Add(tb.IdTransaksiPembayaran);
                    //    }
                    //}
                    //else
                    //{
                    //    original = context.Transaksi.CreateObject();
                    //    context.Transaksi.AddObject(original);
                    //    //TODO: Id Cabang & User
                    //    original.IdCabang = Int32.Parse(ConfigurationManager.AppSettings["IdCabang"].ToString());
                    //    original.WaktuBuat = DateTime.Now;
                    //    //originalTransaksi.IdUser = SessionController.Instance.LoggedUserId;
                    //    original.LastUpdated = DateTime.Now;
                    //}
                    //original.IdKonsumen = ttvm.IdKonsumen;
                    //original.WaktuSelesai = ttvm.WaktuSelesai;
                    //original.TotalHarga = ttvm.TotalHarga;
                    //original.PotonganHarga = ttvm.TotalPotongan;
                    //original.KoreksiHarga = ttvm.KoreksiHarga;
                    //original.IsBatal = ttvm.IsBatal;

                    //if (original.EntityState == EntityState.Modified)
                    //{
                    //    //originalTransaksi.IdUser = SessionController.Instance.LoggedUserId;
                    //    original.LastUpdated = DateTime.Now;
                    //}

                    //TransaksiLayanan originalTL = null;
                    //foreach (TransaksiLayananThumbnailViewModel tltvm in ttvm.TransaksiLayanans)
                    //{
                    //    if (originalTLs.Remove(tltvm.IdTransaksiLayanan))
                    //    {
                    //        originalTL = original.TransaksiLayanan.First(
                    //            tl => tl.IdTransaksiLayanan == tltvm.IdTransaksiLayanan);
                    //    }
                    //    else
                    //    {
                    //        originalTL = context.TransaksiLayanan.CreateObject();
                    //        context.TransaksiLayanan.AddObject(originalTL);
                    //        original.TransaksiLayanan.Add(originalTL);
                    //        originalTL.WaktuBuat = DateTime.Now;
                    //        //originalTL.IdUser = SessionController.Instance.LoggedUserId;
                    //        originalTL.LastUpdated = DateTime.Now;
                    //    }
                    //    originalTL.IdLayanan = tltvm.IdLayanan;
                    //    originalTL.HargaLayanan = tltvm.HargaLayanan;
                    //    originalTL.IdKaryawan = tltvm.IdKaryawan;
                    //    originalTL.NamaPromo = tltvm.NamaPromo;
                    //    originalTL.PotonganPromo = tltvm.PotonganPromo;
                    //    originalTL.NamaFreeGift = tltvm.NamaFreeGift;
                    //    originalTL.IdJenisStok = tltvm.IdJenisStok;
                    //    originalTL.JumlahFreeGift = tltvm.JumlahFreeGift;
                    //    originalTL.WaktuBuat = tltvm.WaktuBuat;
                    //    originalTL.WaktuTunggu = tltvm.WaktuTunggu;
                    //    originalTL.WaktuMulai = tltvm.WaktuMulai;
                    //    originalTL.WaktuSelesai = tltvm.WaktuSelesai;
                    //    originalTL.IsBatal = tltvm.IsBatal;

                    //    if (originalTL.EntityState == EntityState.Modified)
                    //    {
                    //        //originalTL.IdUser = SessionController.Instance.LoggedUserId;
                    //        originalTL.LastUpdated = DateTime.Now;
                    //    }
                    //}
                    ////clearing
                    //foreach (int removedId in originalTLs)
                    //{
                    //    context.TransaksiLayanan.DeleteObject(
                    //        original.TransaksiLayanan.First(
                    //            tl => tl.IdTransaksiLayanan == removedId));
                    //}

                    //TransaksiProduk originalTP = null;
                    //foreach (TransaksiProdukThumbnailViewModel tptvm in ttvm.TransaksiProduks)
                    //{
                    //    if (originalTPs.Remove(tptvm.IdTransaksiProduk))
                    //    {
                    //        originalTP = original.TransaksiProduk.First(
                    //            tp => tp.IdTransaksiProduk == tptvm.IdTransaksiProduk);
                    //    }
                    //    else
                    //    {
                    //        originalTP = context.TransaksiProduk.CreateObject();
                    //        context.TransaksiProduk.AddObject(originalTP);
                    //        original.TransaksiProduk.Add(originalTP);
                    //        //originalTP.IdUser = SessionController.Instance.LoggedUserId;
                    //        originalTP.LastUpdated = DateTime.Now;
                    //    }
                    //    originalTP.IdJenisStok = tptvm.IdJenisStok;
                    //    originalTP.IdKaryawan = tptvm.IdKaryawan;
                    //    originalTP.JumlahProduk = tptvm.JumlahProduk;
                    //    originalTP.HargaProduk = tptvm.HargaProduk;
                    //    originalTP.PotonganHarga = tptvm.PotonganHarga;

                    //    if (originalTP.EntityState == EntityState.Modified)
                    //    {
                    //        //originalTP.IdUser = SessionController.Instance.LoggedUserId;
                    //        originalTP.LastUpdated = DateTime.Now;
                    //    }
                    //}
                    ////clearing
                    //foreach (int removedId in originalTPs)
                    //{
                    //    context.TransaksiProduk.DeleteObject(
                    //        original.TransaksiProduk.First(
                    //            tp => tp.IdTransaksiProduk == removedId));
                    //}

                    //TransaksiPembayaran originalTB = null;
                    //foreach (TransaksiPembayaranThumbnailViewModel tbtvm in ttvm.TransaksiPembayarans)
                    //{
                    //    if (originalTBs.Remove(tbtvm.IdTransaksiPembayaran))
                    //    {
                    //        originalTB = original.TransaksiPembayaran.First(
                    //            tb => tb.IdTransaksiPembayaran == tbtvm.IdTransaksiPembayaran);
                    //    }
                    //    else
                    //    {
                    //        originalTB = context.TransaksiPembayaran.CreateObject();
                    //        context.TransaksiPembayaran.AddObject(originalTB);
                    //        original.TransaksiPembayaran.Add(originalTB);
                    //        //originalTB.IdUser = SessionController.Instance.LoggedUserId;
                    //        originalTB.LastUpdated = DateTime.Now;
                    //    }
                    //    originalTB.IdJenisPembayaran = tbtvm.IdJenisPembayaran;
                    //    originalTB.NominalPembayaran = tbtvm.NominalPembayaran;

                    //    if (originalTB.EntityState == EntityState.Modified)
                    //    {
                    //        //originalTB.IdUser = SessionController.Instance.LoggedUserId;
                    //        originalTB.LastUpdated = DateTime.Now;
                    //    }
                    //}
                    ////clearing
                    //foreach (int removedId in originalTBs)
                    //{
                    //    context.TransaksiPembayaran.DeleteObject(
                    //        original.TransaksiPembayaran.First(
                    //            tl => tl.IdTransaksiPembayaran == removedId));
                    //}
                    //context.SaveChanges();

                    ////update ids ++ synch
                    //SynchTransaksiToTTVM(original, ttvm);
                    //retval = ttvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private CabangViewModel LoadCabangVMInternal(CabangViewModel cvm)
        {
            CabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang original = (from cabang in context.Cabang
                                       where cabang.IdCabang == cvm.IdCabang.DataValue
                                       select cabang).First();
                    SynchCabangToCVM(original, cvm);
                    retval = cvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private CabangViewModel SaveCabangVMInternal(CabangViewModel cvm)
        {
            CabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang original = null;
                    List<int> originalCLs = new List<int>();
                    List<int> originalCPs = new List<int>();
                    List<int> originalPs = new List<int>();
                    List<int> originalFs = new List<int>();
                    List<int> originalAs = new List<int>();
                    List<int> originalSs = new List<int>();
                    if (cvm.IdCabang.DataValue != 0)
                    {
                        original = (from cabang in context.Cabang
                                    where cabang.IdCabang == cvm.IdCabang.DataValue
                                    select cabang).FirstOrDefault();
                        foreach (var cl in original.CabangLayanan)
                        {
                            originalCLs.Add(cl.IdLayanan);
                        }
                        foreach (var cp in original.CabangProduk)
                        {
                            originalCPs.Add(cp.IdJenisStok);
                        }
                        foreach (var pr in original.Promo)
                        {
                            originalPs.Add(pr.IdPromo);
                        }
                        foreach (var fg in original.FreeGift)
                        {
                            originalFs.Add(fg.IdFreeGift);
                        }
                        foreach (var ass in original.Aset)
                        {
                            originalAs.Add(ass.IdAset);
                        }
                        foreach (var stk in original.Stok)
                        {
                            originalSs.Add(stk.IdStok);
                        }
                    }
                    else
                    {
                        original = context.Cabang.CreateObject();
                        context.Cabang.AddObject(original);
                        //TODO: Id Cabang & User
                        //originalTransaksi.IdUser = SessionController.Instance.LoggedUserId;
                        original.LastUpdated = DateTime.Now;
                    }
                    original.Nama = cvm.Nama.DataValue;
                    original.Alamat = cvm.Alamat.DataValue;
                    original.IsGudang = cvm.IsGudang.DataValue;

                    if (original.EntityState == EntityState.Modified)
                    {
                        //originalTransaksi.IdUser = SessionController.Instance.LoggedUserId;
                        original.LastUpdated = DateTime.Now;
                    }

                    #region Synch CabangLayanan
                    CabangLayanan originalCL = null;
                    foreach (CabangLayananViewModel lcvm in cvm.CabangLayanans)
                    {
                        if (originalCLs.Remove(lcvm.IdLayanan.DataValue))
                        {
                            originalCL = original.CabangLayanan.First(
                                cl => cl.IdLayanan == lcvm.IdLayanan.DataValue);
                        }
                        else
                        {
                            originalCL = context.CabangLayanan.CreateObject();
                            context.CabangLayanan.AddObject(originalCL);
                            original.CabangLayanan.Add(originalCL);
                            //originalCL.IdUser = SessionController.Instance.LoggedUserId;
                            originalCL.LastUpdated = DateTime.Now;
                        }
                        originalCL.HargaLayanan = lcvm.Harga.DataValue;

                        if (originalCL.EntityState == EntityState.Modified)
                        {
                            //originalCL.IdUser = SessionController.Instance.LoggedUserId;
                            originalCL.LastUpdated = DateTime.Now;
                        }
                    }
                    //clearing
                    foreach (int removedId in originalCLs)
                    {
                        context.CabangLayanan.DeleteObject(
                            original.CabangLayanan.First(
                                tl => tl.IdLayanan == removedId));
                    }
                    #endregion

                    #region Synch Cabang Produk
                    CabangProduk originalCP = null;
                    foreach (CabangProdukViewModel pcvm in cvm.CabangProduks)
                    {
                        if (originalCPs.Remove(pcvm.IdJenisStok.DataValue))
                        {
                            originalCP = original.CabangProduk.First(
                                cp => cp.IdJenisStok == pcvm.IdJenisStok.DataValue);
                        }
                        else
                        {
                            originalCP = context.CabangProduk.CreateObject();
                            context.CabangProduk.AddObject(originalCP);
                            original.CabangProduk.Add(originalCP);
                            //originalCP.IdUser = SessionController.Instance.LoggedUserId;
                            originalCP.LastUpdated = DateTime.Now;
                        }
                        originalCP.HargaProduk = pcvm.Harga.DataValue;

                        if (originalCP.EntityState == EntityState.Modified)
                        {
                            //originalCP.IdUser = SessionController.Instance.LoggedUserId;
                            originalCP.LastUpdated = DateTime.Now;
                        }
                    }
                    //clearing
                    foreach (int removedId in originalCPs)
                    {
                        context.CabangProduk.DeleteObject(
                            original.CabangProduk.First(
                                cp => cp.IdJenisStok == removedId));
                    }
                    #endregion

                    #region Synch Promo
                    Promo originalP = null;
                    foreach (PromoViewModel pvm in cvm.Promos)
                    {
                        if (originalPs.Remove(pvm.IdPromo.DataValue))
                        {
                            originalP = original.Promo.First(
                                prm => prm.IdPromo == pvm.IdPromo.DataValue);
                        }
                        else
                        {
                            originalP = context.Promo.CreateObject();
                            context.Promo.AddObject(originalP);
                            original.Promo.Add(originalP);
                            //originalP.IdUser = SessionController.Instance.LoggedUserId;
                            originalP.LastUpdated = DateTime.Now;
                        }
                        //todo
                        originalP.Nama = pvm.Nama.DataValue;

                        if (originalP.EntityState == EntityState.Modified)
                        {
                            //originalTB.IdUser = SessionController.Instance.LoggedUserId;
                            originalP.LastUpdated = DateTime.Now;
                        }
                    }
                    //clearing
                    foreach (int removedId in originalPs)
                    {
                        context.Promo.DeleteObject(
                            original.Promo.First(
                                tl => tl.IdPromo == removedId));
                    }
                    #endregion

                    #region Synch Free Gift
                    #endregion

                    #region Synch Aset
                    #endregion
                    
                    #region Synch Stok
                    #endregion

                    context.SaveChanges();
                    //reload update ids ++ synch
                    SynchCabangToCVM(original, cvm);
                    retval = cvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private CabangViewModel RemoveCabangVMInternal(CabangViewModel tvm)
        {
            CabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = null;
                    retval = tvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        #endregion



        #region PrivateMethods [NEW]
        private List<SimpleCabangViewModel> FetchCabangsInternal(int page)
        {
            List<SimpleCabangViewModel> retval = new List<SimpleCabangViewModel>();
            try
            {
                int pageSize = Int32.Parse(ConfigurationManager.AppSettings["LazyLoadPageSize"].ToString());
                using (AnataEntities context = new AnataEntities())
                {
                    var query = from cabang in context.Cabang
                                orderby cabang.Nama
                                select cabang;
                    SimpleCabangViewModel scvm = null;
                    foreach (var originalC in query.Skip(page * pageSize).Take(pageSize).ToList())
                    {
                        scvm = new SimpleCabangViewModel();
                        scvm.Cabang = originalC;
                        retval.Add(scvm);
                    }
                }
            }
            catch (Exception) { }
            return retval;
        }

        private ComplexCabangViewModel LoadCompleteCabangInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = (from cabang in context.Cabang
                                        where cabang.IdCabang == ccvm.LoadedCabang.IdCabang
                                        select cabang).First();
                    SynchCCVMFromCabang(originalC, ccvm, context);
                    SynchCCVMFromCabangLayanan(originalC, ccvm, context);
                    SynchCCVMFromCabangProduk(originalC, ccvm, context);
                    SynchCCVMFromCabangRekening(originalC, ccvm, context);
                    SynchCCVMFromFreeGift(originalC, ccvm, context);
                    SynchCCVMFromPromo(originalC, ccvm, context);
                    SynchCCVMFromAset(originalC, ccvm, context);
                    SynchCCVMFromStok(originalC, ccvm, context);
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private ComplexCabangViewModel LoadCabangInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = LoadCabang(ccvm, context);
                    SynchCCVMFromCabang(originalC, ccvm, context);
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private ComplexCabangViewModel LoadCabangLayananInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = LoadCabang(ccvm, context);
                    SynchCCVMFromCabangLayanan(originalC, ccvm, context);
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private ComplexCabangViewModel LoadCabangProdukInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = LoadCabang(ccvm, context);
                    SynchCCVMFromCabangProduk(originalC, ccvm, context);
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private ComplexCabangViewModel LoadCabangRekeningInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = LoadCabang(ccvm, context);
                    SynchCCVMFromCabangRekening(originalC, ccvm, context);
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private ComplexCabangViewModel LoadFreeGiftInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = LoadCabang(ccvm, context);
                    SynchCCVMFromFreeGift(originalC, ccvm, context);
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private ComplexCabangViewModel LoadPromoInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = LoadCabang(ccvm, context);
                    SynchCCVMFromPromo(originalC, ccvm, context);
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private ComplexCabangViewModel LoadAsetInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = LoadCabang(ccvm, context);
                    SynchCCVMFromAset(originalC, ccvm, context);
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private ComplexCabangViewModel LoadStokInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = LoadCabang(ccvm, context);
                    SynchCCVMFromStok(originalC, ccvm, context);
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }

        private ComplexCabangViewModel SaveCompleteCabangInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = CreateOrLoadCabang(ccvm, context);
                    SynchCCVMToCabang(originalC, ccvm, context);
                    SynchCCVMToCabangLayanan(originalC, ccvm, context);
                    SynchCCVMToCabangProduk(originalC, ccvm, context);
                    SynchCCVMToCabangRekening(originalC, ccvm, context);
                    SynchCCVMToFreeGift(originalC, ccvm, context);
                    SynchCCVMToPromo(originalC, ccvm, context);
                    SynchCCVMToAset(originalC, ccvm, context);
                    SynchCCVMToStok(originalC, ccvm, context);
                    context.SaveChanges();
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private ComplexCabangViewModel SaveCabangInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = CreateOrLoadCabang(ccvm, context);
                    SynchCCVMToCabang(originalC, ccvm, context);
                    context.SaveChanges();
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private ComplexCabangViewModel SaveCabangLayananInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = CreateOrLoadCabang(ccvm, context);
                    SynchCCVMToCabangLayanan(originalC, ccvm, context);
                    context.SaveChanges();
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private ComplexCabangViewModel SaveCabangProdukInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = CreateOrLoadCabang(ccvm, context);
                    SynchCCVMToCabangProduk(originalC, ccvm, context);
                    context.SaveChanges();
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private ComplexCabangViewModel SaveCabangRekeningInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = CreateOrLoadCabang(ccvm, context);
                    SynchCCVMToCabangRekening(originalC, ccvm, context);
                    context.SaveChanges();
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private ComplexCabangViewModel SaveFreeGiftInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = CreateOrLoadCabang(ccvm, context);
                    SynchCCVMToFreeGift(originalC, ccvm, context);
                    context.SaveChanges();
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private ComplexCabangViewModel SavePromoInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = CreateOrLoadCabang(ccvm, context);
                    SynchCCVMToPromo(originalC, ccvm, context);
                    context.SaveChanges();
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private ComplexCabangViewModel SaveAsetInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = CreateOrLoadCabang(ccvm, context);
                    SynchCCVMToAset(originalC, ccvm, context);
                    context.SaveChanges();
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private ComplexCabangViewModel SaveStokInternal(ComplexCabangViewModel ccvm)
        {
            ComplexCabangViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Cabang originalC = CreateOrLoadCabang(ccvm, context);
                    SynchCCVMToStok(originalC, ccvm, context);
                    context.SaveChanges();
                    retval = ccvm;
                }
            }
            catch (Exception) { }
            return retval;
        }



        private PopupStokViewModel LoadCompleteStokInternal(PopupStokViewModel psvm)
        {
            PopupStokViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Stok originalS = LoadStok(psvm, context);
                    SynchPSVMFromStok(originalS, psvm, context);
                    SynchPSVMFromMutasiStok(originalS, psvm, context);
                    retval = psvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private PopupStokViewModel LoadStokInternal(PopupStokViewModel psvm)
        {
            PopupStokViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Stok originalS = LoadStok(psvm, context);
                    SynchPSVMFromStok(originalS, psvm, context);
                    retval = psvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private PopupStokViewModel LoadMutasiStokInternal(PopupStokViewModel psvm)
        {
            PopupStokViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Stok originalS = LoadStok(psvm, context);
                    SynchPSVMFromMutasiStok(originalS, psvm, context);
                    retval = psvm;
                }
            }
            catch (Exception) { }
            return retval;
        }

        private PopupStokViewModel SaveCompleteStokInternal(PopupStokViewModel psvm)
        {
            PopupStokViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Stok originalS = CreateOrLoadStok(psvm, context);
                    SynchPSVMToStok(originalS, psvm, context);
                    SynchPSVMToMutasiStok(originalS, psvm, context);
                    context.SaveChanges();
                    retval = psvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private PopupStokViewModel SaveStokInternal(PopupStokViewModel psvm)
        {
            PopupStokViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Stok originalS = CreateOrLoadStok(psvm, context);
                    SynchPSVMToStok(originalS, psvm, context);
                    context.SaveChanges();
                    retval = psvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        private PopupStokViewModel SaveMutasiStokInternal(PopupStokViewModel psvm)
        {
            PopupStokViewModel retval = null;
            try
            {
                using (AnataEntities context = new AnataEntities())
                {
                    Stok originalS = CreateOrLoadStok(psvm, context);
                    SynchPSVMToMutasiStok(originalS, psvm, context);
                    context.SaveChanges();
                    retval = psvm;
                }
            }
            catch (Exception) { }
            return retval;
        }
        #endregion

        #region Initializer
        private Cabang LoadCabang(ComplexCabangViewModel ccvm, AnataEntities context)
        {
            Cabang originalC = (from cabang in context.Cabang
                                where cabang.IdCabang == ccvm.LoadedCabang.IdCabang
                                select cabang).First();
            return originalC;
        }
        private Cabang CreateOrLoadCabang(ComplexCabangViewModel ccvm, AnataEntities context)
        {
            Cabang originalC = null;
            if (ccvm.IdCabang.DataValue != 0)
            {
                originalC = (from cabang in context.Cabang
                             where cabang.IdCabang == ccvm.IdCabang.DataValue
                             select cabang).First();
            }
            else
            {
                originalC = context.Cabang.CreateObject();
                context.Cabang.AddObject(originalC);
                //TODO: Id Cabang & User
                //originalC.IdUser = SessionController.Instance.LoggedUserId;
                originalC.LastUpdated = DateTime.Now;
            }
            return originalC;
        }

        private Stok LoadStok(PopupStokViewModel psvm, AnataEntities context)
        {
            Stok originalS = (from stok in context.Stok
                              where stok.IdStok == psvm.LoadedStok.IdStok
                              select stok).First();
            return originalS;
        }
        private Stok CreateOrLoadStok(PopupStokViewModel psvm, AnataEntities context)
        {
            Stok originalS = null;
            if (psvm.IdStok.DataValue != 0)
            {
                originalS = LoadStok(psvm, context);
            }
            else
            {
                originalS = context.Stok.CreateObject();
                context.Stok.AddObject(originalS);
                //TODO: Id Cabang & User
                //originalS.IdUser = SessionController.Instance.LoggedUserId;
                originalS.LastUpdated = DateTime.Now;
            }
            return originalS;
        }
        #endregion
        
        #region PrivateMethods.Synchronizer
        private void SynchCabangToCTVM(Cabang original, CabangThumbnailViewModel ctvm)
        {
            ctvm.IdCabang = original.IdCabang;
            ctvm.Nama = original.Nama;
            ctvm.Alamat = original.Alamat;
            ctvm.IsGudang = original.IsGudang;
        }
        private void SynchCabangToCVM(Cabang original, CabangViewModel cvm)
        {
            cvm.IdCabang.DataValue = original.IdCabang;
            cvm.Nama.DataValue = original.Nama;
            cvm.Alamat.DataValue = original.Alamat;
            cvm.IsGudang.DataValue = original.IsGudang;

            #region Synch Cabang Layanan
            cvm.CabangLayanans.Clear();
            CabangLayananViewModel lcvm = null;
            foreach (var cl in original.CabangLayanan)
            {
                lcvm = cvm.ForceCreateChildLayananCabangVM();
                lcvm.IdCabang.DataValue = cl.IdCabang;
                //lcvm.NamaCabang = cl.Cabang.Nama;
                lcvm.IdLayanan.DataValue = cl.IdLayanan;
                lcvm.NamaLayanan = cl.Layanan.Nama;
                lcvm.Harga.DataValue = cl.HargaLayanan;
                cvm.CabangLayanans.Add(lcvm);
            }
            #endregion

            #region Synch Cabang Produk
            cvm.CabangProduks.Clear();
            CabangProdukViewModel pcvm = null;
            foreach (var cp in original.CabangProduk)
            {
                pcvm = cvm.ForceCreateChildProdukCabangVM();
                pcvm.IdCabang.DataValue = cp.IdCabang;
                //pcvm.NamaCabang = cp.Cabang.Nama;
                pcvm.IdJenisStok.DataValue = cp.IdJenisStok;
                pcvm.NamaJenisStok = cp.JenisStok.Nama;
                pcvm.Harga.DataValue = cp.HargaProduk;
                cvm.CabangLayanans.Add(lcvm);
            }
            #endregion

            #region Synch Promo
            cvm.Promos.Clear();
            PromoViewModel pvm = null;
            foreach (var prm in original.Promo)
            {
                pvm = cvm.ForceCreateChildPromoVM();
                pvm.IdPromo.DataValue = prm.IdPromo;
                pvm.IdLayanan.DataValue = prm.IdLayanan;
                pvm.IdCabang.DataValue = prm.IdCabang;
                pvm.Nama.DataValue = prm.Nama;
                cvm.Promos.Add(pvm);
            }
            #endregion

            #region Synch Free Gift
            #endregion
            #region Synch Aset
            #endregion
            #region Synch Stok
            #endregion
        }
        #endregion



        #region Synchronizer [New]
        private void SynchCCVMToCabang(Cabang originalC, ComplexCabangViewModel ccvm, AnataEntities context)
        {
            originalC.Nama = ccvm.Nama.DataValue;
            originalC.Alamat = ccvm.Alamat.DataValue;
            originalC.IsGudang = ccvm.IsGudang.DataValue;

            if (originalC.EntityState == EntityState.Modified)
            {
                //originalC.IdUser = SessionController.Instance.LoggedUserId;
                originalC.LastUpdated = DateTime.Now;
            }
        }
        private void SynchCCVMToCabangLayanan(Cabang originalC, ComplexCabangViewModel ccvm, AnataEntities context)
        {
            CabangLayanan originalCL = null;
            foreach (ComplexCabangLayananViewModel cclvm in ccvm.CabangLayanans)
            {
                if (cclvm.IdCabang.DataValue != 0 && cclvm.IdLayanan.DataValue != 0)
                {
                    originalCL = (from cl in originalC.CabangLayanan
                                  where cl.IdLayanan == cclvm.IdLayanan.DataValue
                                  select cl).First();
                }
                else
                {
                    originalCL = context.CabangLayanan.CreateObject();
                    context.CabangLayanan.AddObject(originalCL);
                    originalC.CabangLayanan.Add(originalCL);
                    //originalCL.IdUser = SessionController.Instance.LoggedUserId;
                    originalCL.LastUpdated = DateTime.Now;
                }

                if (!cclvm.IsDeleted.DataValue)
                {
                    originalCL.IdLayanan = cclvm.IdLayanan.DataValue;
                    originalCL.HargaLayanan = cclvm.HargaLayanan.DataValue;

                    if (originalCL.EntityState == EntityState.Modified)
                    {
                        //originalCL.IdUser = SessionController.Instance.LoggedUserId;
                        originalCL.LastUpdated = DateTime.Now;
                    }
                }
                else
                {
                    context.CabangLayanan.DeleteObject(
                        originalC.CabangLayanan.First(
                            kl => kl.IdLayanan == cclvm.IdLayanan.DataValue));
                }
            }
        }
        private void SynchCCVMToCabangProduk(Cabang originalC, ComplexCabangViewModel ccvm, AnataEntities context)
        {
            CabangProduk originalCP = null;
            foreach (ComplexCabangProdukViewModel ccpvm in ccvm.CabangProduks)
            {
                if (ccpvm.IdCabang.DataValue != 0 && ccpvm.IdJenisStok.DataValue != 0)
                {
                    originalCP = (from cp in originalC.CabangProduk
                                  where cp.IdJenisStok == ccpvm.IdJenisStok.DataValue
                                  select cp).First();
                }
                else
                {
                    originalCP = context.CabangProduk.CreateObject();
                    context.CabangProduk.AddObject(originalCP);
                    originalC.CabangProduk.Add(originalCP);
                    //originalCP.IdUser = SessionController.Instance.LoggedUserId;
                    originalCP.LastUpdated = DateTime.Now;
                }

                if (!ccpvm.IsDeleted.DataValue)
                {
                    originalCP.IdJenisStok = ccpvm.IdJenisStok.DataValue;
                    originalCP.HargaProduk = ccpvm.HargaProduk.DataValue;

                    if (originalCP.EntityState == EntityState.Modified)
                    {
                        //originalCP.IdUser = SessionController.Instance.LoggedUserId;
                        originalCP.LastUpdated = DateTime.Now;
                    }
                }
                else
                {
                    context.CabangProduk.DeleteObject(
                        originalC.CabangProduk.First(
                            kl => kl.IdJenisStok == ccpvm.IdJenisStok.DataValue));
                }
            }
        }
        private void SynchCCVMToCabangRekening(Cabang originalC, ComplexCabangViewModel ccvm, AnataEntities context)
        {
            CabangRekening originalCR = null;
            foreach (ComplexCabangRekeningViewModel ccrvm in ccvm.CabangRekenings)
            {
                if (ccrvm.IdCabang.DataValue != 0 && ccrvm.IdRekening.DataValue != 0)
                {
                    originalCR = (from cp in originalC.CabangRekening
                                  where cp.IdRekening == ccrvm.IdRekening.DataValue
                                  select cp).First();
                }
                else
                {
                    originalCR = context.CabangRekening.CreateObject();
                    context.CabangRekening.AddObject(originalCR);
                    originalC.CabangRekening.Add(originalCR);
                    //originalCR.IdUser = SessionController.Instance.LoggedUserId;
                    originalCR.LastUpdated = DateTime.Now;
                }

                if (!ccrvm.IsDeleted.DataValue)
                {
                    originalCR.IdRekening = ccrvm.IdRekening.DataValue;

                    if (originalCR.EntityState == EntityState.Modified)
                    {
                        //originalCR.IdUser = SessionController.Instance.LoggedUserId;
                        originalCR.LastUpdated = DateTime.Now;
                    }
                }
                else
                {
                    context.CabangRekening.DeleteObject(
                        originalC.CabangRekening.First(
                            kl => kl.IdRekening == ccrvm.IdRekening.DataValue));
                }
            }
        }
        private void SynchCCVMToFreeGift(Cabang originalC, ComplexCabangViewModel ccvm, AnataEntities context)
        {
            FreeGift originalF = null;
            foreach (ComplexFreeGiftViewModel cfvm in ccvm.FreeGifts)
            {
                if (cfvm.IdFreeGift.DataValue != 0)
                {
                    originalF = (from cp in originalC.FreeGift
                                 where cp.IdFreeGift == cfvm.IdFreeGift.DataValue
                                 select cp).First();
                }
                else
                {
                    originalF = context.FreeGift.CreateObject();
                    context.FreeGift.AddObject(originalF);
                    originalC.FreeGift.Add(originalF);
                    //originalF.IdUser = SessionController.Instance.LoggedUserId;
                    originalF.LastUpdated = DateTime.Now;
                }

                if (!cfvm.IsDeleted.DataValue)
                {
                    originalF.IdLayanan = cfvm.IdLayanan.DataValue;
                    //originalF.IdCabang = cfvm.IdCabang.DataValue;
                    originalF.Nama = cfvm.Nama.DataValue;
                    originalF.IdJenisStok = cfvm.IdJenisStok.DataValue;
                    originalF.Jumlah = cfvm.Jumlah.DataValue;
                    originalF.IsAktif = cfvm.IsAktif.DataValue;

                    if (originalF.EntityState == EntityState.Modified)
                    {
                        //originalF.IdUser = SessionController.Instance.LoggedUserId;
                        originalF.LastUpdated = DateTime.Now;
                    }
                }
                else
                {
                    context.FreeGift.DeleteObject(
                        originalC.FreeGift.First(
                            kl => kl.IdFreeGift == cfvm.IdFreeGift.DataValue));
                }
            }
        }
        private void SynchCCVMToPromo(Cabang originalC, ComplexCabangViewModel ccvm, AnataEntities context)
        {
            Promo originalP = null;
            foreach (ComplexPromoViewModel cpvm in ccvm.Promos)
            {
                if (cpvm.IdPromo.DataValue != 0)
                {
                    originalP = (from p in originalC.Promo
                                 where p.IdPromo == cpvm.IdPromo.DataValue
                                 select p).First();
                }
                else
                {
                    originalP = context.Promo.CreateObject();
                    context.Promo.AddObject(originalP);
                    originalC.Promo.Add(originalP);
                    //originalP.IdUser = SessionController.Instance.LoggedUserId;
                    originalP.LastUpdated = DateTime.Now;
                }

                if (!cpvm.IsDeleted.DataValue)
                {
                    originalP.IdLayanan = cpvm.IdLayanan.DataValue;
                    //originalP.IdCabang = cpvm.IdCabang.DataValue;
                    originalP.Nama = cpvm.Nama.DataValue;
                    originalP.IsPersentase = cpvm.IsPersentase.DataValue;
                    originalP.PersentasePromo = (float)cpvm.PersentasePromo.DataValue;
                    originalP.NominalPromo = cpvm.NominalPromo.DataValue;
                    originalP.Syarat = cpvm.Syarat.DataValue;
                    originalP.IsOnce = cpvm.IsOnce.DataValue;
                    originalP.IsDaily = cpvm.IsDaily.DataValue;
                    originalP.IsWeekly = cpvm.IsWeekly.DataValue;
                    originalP.IsMonthly = cpvm.IsMonthly.DataValue;
                    originalP.IsYearly = cpvm.IsYearly.DataValue;
                    originalP.WaktuMulai = cpvm.WaktuMulai.DataValue;
                    originalP.WaktuSelesai = cpvm.WaktuSelesai.DataValue;

                    if (originalP.EntityState == EntityState.Modified)
                    {
                        //originalP.IdUser = SessionController.Instance.LoggedUserId;
                        originalP.LastUpdated = DateTime.Now;
                    }
                }
                else
                {
                    context.Promo.DeleteObject(
                        originalC.Promo.First(
                            kl => kl.IdPromo == cpvm.IdPromo.DataValue));
                }
            }
        }
        private void SynchCCVMToAset(Cabang originalC, ComplexCabangViewModel ccvm, AnataEntities context)
        {
            Aset originalA = null;
            foreach (ComplexAsetViewModel cavm in ccvm.Asets)
            {
                if (cavm.IdAset.DataValue != 0)
                {
                    originalA = (from a in originalC.Aset
                                 where a.IdAset == cavm.IdAset.DataValue
                                 select a).First();
                }
                else
                {
                    originalA = context.Aset.CreateObject();
                    context.Aset.AddObject(originalA);
                    originalC.Aset.Add(originalA);
                    //originalA.IdUser = SessionController.Instance.LoggedUserId;
                    originalA.LastUpdated = DateTime.Now;
                }

                if (!cavm.IsDeleted.DataValue)
                {
                    originalA.IdJenisAset = cavm.IdJenisAset.DataValue;
                    //originalA.IdCabang = cavm.IdCabang.DataValue;
                    originalA.Nama = cavm.Nama.DataValue;
                    originalA.HargaBeli = cavm.HargaBeli.DataValue;
                    originalA.WaktuBeli = cavm.WaktuBeli.DataValue;
                    originalA.HargaJual = cavm.HargaJual.DataValue;
                    originalA.WaktuJual = cavm.WaktuJual.DataValue;
                    originalA.Amortisasi = cavm.Amortisasi.DataValue;

                    if (originalA.EntityState == EntityState.Modified)
                    {
                        //originalA.IdUser = SessionController.Instance.LoggedUserId;
                        originalA.LastUpdated = DateTime.Now;
                    }
                }
                else
                {
                    context.Aset.DeleteObject(
                        originalC.Aset.First(
                            kl => kl.IdAset == cavm.IdAset.DataValue));
                }
            }
        }
        private void SynchCCVMToStok(Cabang originalC, ComplexCabangViewModel ccvm, AnataEntities context)
        {
            Stok originalS = null;
            foreach (ComplexStokViewModel csvm in ccvm.Stoks)
            {
                if (csvm.IdStok.DataValue != 0)
                {
                    originalS = (from s in originalC.Stok
                                 where s.IdStok == csvm.IdStok.DataValue
                                 select s).First();
                }
                else
                {
                    originalS = context.Stok.CreateObject();
                    context.Stok.AddObject(originalS);
                    originalC.Stok.Add(originalS);
                    //originalS.IdUser = SessionController.Instance.LoggedUserId;
                    originalS.LastUpdated = DateTime.Now;
                }

                if (!csvm.IsDeleted.DataValue)
                {
                    originalS.IdJenisStok = csvm.IdJenisStok.DataValue;
                    //originalS.IdCabang = csvm.IdCabang.DataValue;
                    originalS.JumlahBeli = csvm.JumlahBeli.DataValue;
                    //originalS.JumlahAktual = csvm.JumlahAktual.DataValue;
                    originalS.HargaBeli = csvm.HargaBeli.DataValue;
                    originalS.WaktuBeli = csvm.WaktuBeli.DataValue;
                    originalS.TanggalKadaluarsa = csvm.TanggalKadaluarsa.DataValue;
                    originalS.Catatan = csvm.Catatan.DataValue;

                    if (originalS.EntityState == EntityState.Modified)
                    {
                        //originalS.IdUser = SessionController.Instance.LoggedUserId;
                        originalS.LastUpdated = DateTime.Now;
                    }
                }
                else
                {
                    context.Stok.DeleteObject(
                        originalC.Stok.First(
                            kl => kl.IdStok == csvm.IdStok.DataValue));
                }
            }
        }

        private void SynchCCVMFromCabang(Cabang originalC, ComplexCabangViewModel ccvm, AnataEntities context)
        {
            ccvm.LoadedCabang = originalC;
        }
        private void SynchCCVMFromCabangLayanan(Cabang originalC, ComplexCabangViewModel ccvm, AnataEntities context)
        {
            ComplexCabangLayananViewModel cclvm = null;
            foreach (var originalCL in originalC.CabangLayanan)
            {
                cclvm = ccvm.ForceCreateChildCCLVM(originalCL, originalCL.Layanan);
            }
        }
        private void SynchCCVMFromCabangProduk(Cabang originalC, ComplexCabangViewModel ccvm, AnataEntities context)
        {
            ComplexCabangProdukViewModel ccpvm = null;
            foreach (var originalCP in originalC.CabangProduk)
            {
                ccpvm = ccvm.ForceCreateChildCCPVM(originalCP, originalCP.JenisStok);
            }
        }
        private void SynchCCVMFromCabangRekening(Cabang originalC, ComplexCabangViewModel ccvm, AnataEntities context)
        {
            ComplexCabangRekeningViewModel ccrvm = null;
            foreach (var originalCR in originalC.CabangRekening)
            {
                ccrvm = ccvm.ForceCreateChildCCRVM(originalCR, originalCR.Rekening);
            }
        }
        private void SynchCCVMFromFreeGift(Cabang originalC, ComplexCabangViewModel ccvm, AnataEntities context)
        {
            ComplexFreeGiftViewModel cfvm = null;
            foreach (var originalF in originalC.FreeGift)
            {
                cfvm = ccvm.ForceCreateChildCFVM(originalF, originalF.Layanan, originalF.JenisStok);
            }
        }
        private void SynchCCVMFromPromo(Cabang originalC, ComplexCabangViewModel ccvm, AnataEntities context)
        {
            ComplexPromoViewModel cpvm = null;
            foreach (var originalP in originalC.Promo)
            {
                cpvm = ccvm.ForceCreateChildCPVM(originalP, originalP.Layanan);
            }
        }
        private void SynchCCVMFromAset(Cabang originalC, ComplexCabangViewModel ccvm, AnataEntities context)
        {
            ComplexAsetViewModel cavm = null;
            foreach (var originalA in originalC.Aset)
            {
                cavm = ccvm.ForceCreateChildCAVM(originalA, originalA.JenisAset);
            }
        }
        private void SynchCCVMFromStok(Cabang originalC, ComplexCabangViewModel ccvm, AnataEntities context)
        {
            ComplexStokViewModel csvm = null;
            foreach (var originalS in originalC.Stok)
            {
                csvm = ccvm.ForceCreateChildCSVM(originalS, originalS.JenisStok);
            }
        }



        private void SynchPSVMToStok(Stok originalS, PopupStokViewModel psvm, AnataEntities context)
        {
            originalS.IdJenisStok = psvm.IdJenisStok.DataValue;
            originalS.IdCabang = psvm.IdCabang.DataValue;
            originalS.JumlahBeli = psvm.JumlahBeli.DataValue;
            //originalS.JumlahAktual = psvm.JumlahAktual.DataValue;
            originalS.HargaBeli = psvm.HargaBeli.DataValue;
            originalS.WaktuBeli = psvm.WaktuBeli.DataValue;
            originalS.TanggalKadaluarsa = psvm.TanggalKadaluarsa.DataValue;
            originalS.Catatan = psvm.Catatan.DataValue;

            if (originalS.EntityState == EntityState.Modified)
            {
                //originalS.IdUser = SessionController.Instance.LoggedUserId;
                originalS.LastUpdated = DateTime.Now;
            }
        }
        private void SynchPSVMToMutasiStok(Stok originalS, PopupStokViewModel psvm, AnataEntities context)
        {
            MutasiStok originalMS = null;
            foreach (ComplexMutasiStokViewModel cmsvm in psvm.MutasiStoks)
            {
                if (cmsvm.IdMutasiStok.DataValue != 0)
                {
                    originalMS = (from ms in originalS.MutasiStok
                                  where ms.IdMutasiStok == cmsvm.IdMutasiStok.DataValue
                                  select ms).First();
                }
                else
                {
                    originalMS = context.MutasiStok.CreateObject();
                    context.MutasiStok.AddObject(originalMS);
                    originalS.MutasiStok.Add(originalMS);
                    //originalMS.IdUser = SessionController.Instance.LoggedUserId;
                    originalMS.LastUpdated = DateTime.Now;
                }

                if (!cmsvm.IsDeleted.DataValue)
                {
                    //originalMS.IdStok = cmsvm.IdStok.DataValue;
                    originalMS.IdJenisMutasiStok = cmsvm.IdJenisMutasiStok.DataValue;
                    originalMS.JumlahMutasi = cmsvm.JumlahMutasi.DataValue;
                    originalMS.WaktuMutasi = cmsvm.WaktuMutasi.DataValue;
                    originalMS.Keterangan = cmsvm.Keterangan.DataValue;

                    if (originalMS.EntityState == EntityState.Modified)
                    {
                        //originalMS.IdUser = SessionController.Instance.LoggedUserId;
                        originalMS.LastUpdated = DateTime.Now;
                    }
                }
                else
                {
                    context.MutasiStok.DeleteObject(
                        originalS.MutasiStok.First(
                            kl => kl.IdMutasiStok == cmsvm.IdMutasiStok.DataValue));
                }
            }
        }

        private void SynchPSVMFromStok(Stok originalS, PopupStokViewModel psvm, AnataEntities context)
        {
            psvm.LoadedStok = originalS;
        }
        private void SynchPSVMFromMutasiStok(Stok originalS, PopupStokViewModel psvm, AnataEntities context)
        {
            ComplexMutasiStokViewModel cmsvm = null;
            foreach (var originalMS in originalS.MutasiStok.OrderByDescending(ms => ms.WaktuMutasi))
            {
                cmsvm = psvm.ForceCreateChildCMSVM(originalMS, originalMS.JenisMutasiStok);
            }
        }
        #endregion
    }
}
